import {get_sign} from './encrypt'
import {getLocVal} from "./utils"
import {apiUrl,API_KEY} from './config'
export const $http_file=(data={})=>{

    if(data.loading !== false){
      Loading.open("上传中...");
    }
      // 基础参数
      const base_params = {
        ticket: getLocVal("ticket") || '',
        ClientSource: 3,
        ClientSystem: navigator.appVersion,
        Version: 3.1,
        app_key: API_KEY
      }
      let query_params = Object.assign({}, base_params, JSON.parse(data.params))
      let sign = get_sign(query_params)
      let commonParams = Object.assign(query_params, {
        sign: sign
      });
      var formData=getFormData()
      for(var k in data.file){
        formData.append(k,data.file[k],data.type)
      }
      for(var i in commonParams){
        formData.append(i,commonParams[i])
      }
  
      return new Promise((resolve,reject)=>{
        var request = new XMLHttpRequest();
        request.open("POST", apiUrl);
        request.send(formData);
        request.onreadystatechange =()=>{
          Loading.close()
          if(request.readyState==4){
            if(request.status==200){
              var response=JSON.parse(request.response);
              if(response.status!=1){
                Toast({
                  mes: response.info,
                  timeout: 1500
                });
  
              }
              return resolve(response)
          }else{
            Toast({
              mes: '服务器异常',
              timeout: 1500
            });
            return reject(response);
          }
        }
      }
    })
  
  }
//   获取FormData
  function getFormData() {
    var isNeedShim = ~navigator.userAgent.indexOf('Android')
        && ~navigator.vendor.indexOf('Google')
        && !~navigator.userAgent.indexOf('Chrome')
        && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;
    return isNeedShim ? new FormDataShim() : new FormData()
  }
  /**
   * formdata 补丁, 给不支持formdata上传blob的android机打补丁
   * @constructor
   */
  function FormDataShim() {
    console.warn('using formdata shim');
    var o = this,
        parts = [],
        boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
        oldSend = XMLHttpRequest.prototype.send;
    this.append = function(name, value, filename) {
      parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');
      if (value instanceof Blob) {
        parts.push('; filename="' + (filename || 'blob') + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
        parts.push(value);
      }
      else {
        parts.push('\r\n\r\n' + value);
      }
      parts.push('\r\n');
    };
    // Override XHR send()
    XMLHttpRequest.prototype.send = function(val) {
      var fr,
          data,
          oXHR = this;
      if (val === o) {
        // Append the final boundary string
        parts.push('--' + boundary + '--\r\n');
        // Create the blob
        data = getBlob(parts);
        // Set up and read the blob into an array to be sent
        fr = new FileReader();
        fr.onload = function() {
          oldSend.call(oXHR, fr.result);
        };
        fr.onerror = function(err) {
          throw err;
        };
        fr.readAsArrayBuffer(data);
        // Set the multipart content type and boudary
        this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
        XMLHttpRequest.prototype.send = oldSend;
      }
      else {
        oldSend.call(this, val);
      }
    };
  }